<template>
<!--    加个搜索框按钮-->
    <div class="community-module">
        <!-- 添加发布文章按钮 -->
        <!-- 将发布文章按钮放到右边       -->
<!--        搜索框-->
      <el-card class="search-bar">
          <el-input v-model="searchQuery.title" placeholder="请输入标题" style="width: 300px;margin-left: 10px"></el-input>
          <el-input v-model="searchQuery.username" placeholder="请输入用户名" style="width: 300px;margin-left: 10px;"></el-input>
          <el-button type="danger" icon="search" @click="searchArticles" style="margin-left: 10px">搜索</el-button>
          <el-button type="warning" icon="search" @click="resetSearch">重置</el-button>

          <div class="header-actions">
              <el-row>
                  <el-button style="margin-top: 10px;margin-left: 8px"  type="primary" round plain
                             @click="showCreateArticle()"><el-icon><Position /></el-icon>发布</el-button>
                  <el-button style="margin-top: 10px;margin-left: 8px"  type="primary" round plain
                             @click="navigateToMyArticles"><el-icon><ChatLineSquare /></el-icon>我的文章</el-button>
              </el-row>
          </div>
      </el-card>


        <!-- 文章列表 -->
        <h2>菜谱</h2>
        <div class="article-list">
            <div v-for="article in articles" :key="article.id" class="article-card" @click="viewArticleDetails(article.id)">
                <div class="article-media">
<!--                    <img :src="'/project/files'+article.imgUrl" alt="Article Image" class="article-image">-->
                    <el-image :src="baseUrl+article.imgUrl" alt="菜谱图片" class="article-image"></el-image>
                </div>
                <div class="article-content-wrapper">
                    <div class="article-header">
                        <h3 class="title">{{ article.title }}</h3>
                        <div class="meta-info">
                            <!--             userId formatter转化-->
                            <span class="user-id">{{ userIdFormatter(article, null, article.userId, null) }}</span>
                            <p>发布日期: {{ article.createTime }}</p>
                        </div>
                    </div>
                    <div class="article-body">
                        <div class="article-content">
                            <p>{{ article.articleSummary }}</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import axios from 'axios';
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElDialog, ElForm, ElFormItem, ElInput, ElUpload, ElIcon, Plus } from 'element-plus';
import qs from "qs";
import router from "@/router";
//获取当前用户信息
const user =getUser();
const baseUrl = getBaseUrl();
//文章列表数据
const articles = ref([
    // {
    //     id: 1,
    //     title: '好吃的好吃的',
    //     content: '鸡肉切块，焯水去血沫。\n' +
    //         '锅中热油，加入干辣椒、八角、花椒、姜、大葱、蒜爆香。\n' +
    //         '加入鸡块翻炒，加入生抽、老抽、豆瓣酱、蚝油调味。\n' +
    //         '加入适量水，放入冰糖，小火炖煮至鸡肉熟烂',
    //     imageUrl: '/image/login/img_1.png',
    //     author: 'John Doe',
    //     publishDate: '2023-05-01',
    //     videoUrl: 'https://example.com/video1.mp4'
    // }
]);


/**
 * 获取文章数据 函数
 */
const searchQuery=ref({
    title:'',
    username:''
});
const fetchArticles = () => {

    axios.get(BASE_URL + '/v1/article/select/')
        .then((response) => {
            if (response.data.code === 2000) {
                // 只保留前10篇文章
                articles.value = response.data.data.slice(0, 10);
            } else {
                ElMessage.error(response.data.msg);
            }
        });
};
onMounted(() => {
    fetchArticles();
});
const searchArticles=()=>{
    console.log("获取文章数据");
    let data = qs.stringify(searchQuery.value);
    console.log(data);
    axios.get(BASE_URL + '/v1/article/select?'+data)
        .then((response) => {
            if (response.data.code === 2000){
                articles.value = response.data.data;
                //formatter方法将后端获取到的文章数据中用户ID 转换为用户名 如101 转换为 user1 102 转换为 user2
                ElMessage.success("搜索成功")
            } else if(response.data.code===4000){
                articles.value=[];
                ElMessage.error("没有找到相关文章");
            }
        else {
                ElMessage.error(response.data.msg);
            }
        });
};

// 用户ID 转换为用户名
const userIdFormatter = (row, column, cellValue, index) => {
    if (cellValue==101){
        return 'user1';
    }else if (cellValue==102){
        return 'user2';
    }else if (cellValue==103){
      return 'user3';
    } else{
        return cellValue;
    }

}

//todo
//重置按钮
const resetSearch=()=> {
    searchQuery.value = {
        title: '',
        username: ''
    }
    searchArticles();
}

/**
 * 查看文章详情
 */
const viewArticleDetails = (id) => {
    console.log(id);
    router.push('/article?id='+id);
};



/**
 * 跳转到“我的文章”页面
 */
const navigateToMyArticles = () => {
    router.push('/my-articles'); // 假设“我的文章”页面的路由路径为 /my-articles
};
const showCreateArticle =()=>{
  //跳转到发布文章的页面
  router.push('/createArticle');
}

/**图片上传相关代码开始**/
const fileList = ref([]);
const dialogImageUrl = ref('');
const dialogVisible = ref(false);
//定义变量用来保存图片上传给哪个后端接口地址
const actionUrl = ref(BASE_URL + '/v1/file/upload');
//移除图片
const handleRemove = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles);
    //1.得到要删除的图片路径 uploadFile就是我们要删除的那个图片文件对象
    let imgUrl = uploadFile.response.data;
    //2.给后端发请求,删除图片
    axios.post(BASE_URL+'/v1/file/remove?imgUrl='+imgUrl)
        .then((response)=>{
            if (response.data.code==2000){
                ElMessage.success('删除成功!');
            }
        })
}
//图片上传后预览
const handlePictureCardPreview = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url
    dialogVisible.value = true;
    console.log(uploadFile);
    //console.log(fileList.value[0].response.data);
}
/**图片上传相关代码结束**/

// 计算属性：截取文章内容
const getShortContent = computed(() => {
    return (content) => {
        if (content.length > 10) {
            return content.slice(0, 10) + '...';
        }
        return content;
    };
});




</script>

<style scoped>

.community-module {
    padding: 20px;
}

.header-actions {
    display: flex;
    justify-content: flex-end; /* 对齐到右侧 */
}



.article-list {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
}

.article-card {
    border: 1px solid #e0e0e0;
    border-radius: 10px;
    overflow: hidden;
    width: 300px;
    cursor: pointer;
    transition: transform 0.2s;
}

.article-card:hover {
    transform: scale(1.1);
}

.article-media {
    width: 100%;
    overflow: hidden;
}

.article-image {
    width: 100%;
    height: auto;
}

.article-content-wrapper {
    padding: 16px;
}

.article-header {
    margin-bottom: 10px;
}

.title {
    font-size: 18px;
    margin: 0 0 8px;
}

.meta-info {
    color: #777;
    font-size: 14px;
    margin: 0;
}

.article-body {
    margin-top: 10px;
}

.search-bar{
    display: flex;
    flex-direction: column;
}
</style>
